package com.ficus.road.maintain.util.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

public class BlockingQueueMonitorDecorator<E> extends BlockingQueueBaseDecorator<E> {
    private LogMonitorCounter.Counter queueSizeCounter;

    public BlockingQueueMonitorDecorator(String queueSizeCounterName,
                                         BlockingQueue<E> blockingQueue) {
        super(blockingQueue);
        this.queueSizeCounter =
                LogMonitorCounter.getCounter(
                        queueSizeCounterName,
                        LogMonitorCounter.CounterType.QPS);
    }

    @Override
    public E poll(long l, TimeUnit timeUnit) throws InterruptedException {
        E item = null;
        item = getBlockingQueue().poll(l, timeUnit);
        if (item != null) {
            queueSizeCounter.addCount(-1);
        }
        return item;
    }

    @Override
    public E take() throws InterruptedException {
        E item = null;
        item = getBlockingQueue().take();
        if (item != null) {
            queueSizeCounter.addCount(-1);
        }
        return item;
    }

    @Override
    public void put(E item) throws InterruptedException {
        queueSizeCounter.addCount(1);
        getBlockingQueue().put(item);
    }

    @Override
    public boolean add(E item) {
        queueSizeCounter.addCount(1);
        return getBlockingQueue().add(item);
    }

    @Override
    public boolean offer(E item) {
        queueSizeCounter.addCount(1);
        if (getBlockingQueue().offer(item)) {
            return true;
        } else {
            queueSizeCounter.addCount(-1);
            return false;
        }
    }
}
